package com.zhida.jiyangcenter.mian.fragment

import android.graphics.Typeface
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.annotation.ContentLayout
import chooongg.base.loadState.LoadService
import chooongg.base.loadState.LoadUtils
import chooongg.base.loadState.callback.EmptyCallback
import chooongg.base.loadState.callback.ErrorCallback
import chooongg.base.loadState.callback.NetworkCallback

import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.base.widget.recyclerView.divider.VerticalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.zhida.jiyangcenter.DEFAULT_ROW
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIShop
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.ProductListEntity
import com.zhida.jiyangcenter.mian.BaseFragment
import com.zhida.jiyangcenter.modle.ShopDetailsActivity
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.list.*

@ContentLayout(R.layout.list)
class MainShopItemFragment : BaseFragment() {
    val adapter = Adapter()
    private var page = 1
    private lateinit var loadService: LoadService<*>
    override fun initConfig(savedInstanceState: Bundle?) {
        super.initConfig(savedInstanceState)
        loadService = LoadUtils.getDefault().register(refresh_layout) {
            page = 1
            getData()
        }
        recycler_view.layoutManager = LinearLayoutManager(context)
        recycler_view.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(requireContext())
                .sizeResId(R.dimen.d10).colorResId(R.color.colorBack).build()
        )
        recycler_view.adapter = adapter
        refresh_layout.setOnRefreshListener {
            page = 1
            getData()
        }
        adapter.setPreLoadNumber(3)
        adapter.setOnLoadMoreListener({
            ++page
            getData()
        }, recycler_view)
        adapter.setOnItemClickListener { _, _, position ->
            startActivity<ShopDetailsActivity> { putExtra("uuid", adapter.data[position].uuid) }
        }
        getData()

    }

    fun search(text: String) {
        searchs = text
        page = 1
        getData()
    }

    var searchs = ""
    private fun getData() {
        lifecycleScope.request({
            APIShop.service()
                .productList(getTitle().toString(), pageNumber = page, search = searchs)
        },
            object : BaseAPI<ProductListEntity>() {
                override fun onSuccess(t: ProductListEntity?, state: Int, msg: String) {
                    if (t != null && !t.product.isNullOrEmpty()) {
                        if (page <= 1) {
                            adapter.setNewData(t.product)
                            loadService.showSuccess()
                            refresh_layout.finishRefresh()
                            if (t.product.size < DEFAULT_ROW) {
                                adapter.loadMoreEnd(true)
                            }
                        } else {
                            adapter.addData(t.product)
                            if (t.product.size < DEFAULT_ROW) {
                                adapter.loadMoreEnd(true)
                            } else adapter.loadMoreComplete()
                        }
                    } else onError(APIException(APIException.Type.EMPTY))
                }

                override fun onError(e: APIException) {
                    if (page <= 1) when (e.type) {
                        APIException.Type.EMPTY -> loadService.showCallback(
                            EmptyCallback::class,
                            "暂无商品"
                        )
                        APIException.Type.ERROR_NETWORK -> loadService.showCallback(NetworkCallback::class)
//                        APIException.Type.NOT_LOGIN -> loadService.showCallback(NotLoginCallback::class)
                        else -> loadService.showCallback(ErrorCallback::class, e.eMessage)
                    } else when (e.type) {
                        APIException.Type.EMPTY -> {
                            adapter.loadMoreFail()
                        }
                        else -> adapter.loadMoreFail()
                    }
                }
            })
    }

    class Adapter :
        BaseQuickAdapter<ProductListEntity.Product, BaseViewHolder>(R.layout.item_main_shop_fragment) {
        override fun convert(helper: BaseViewHolder, item: ProductListEntity.Product?) {
            helper.setText(R.id.tv_main_shop_name, item?.name)
                .setText(R.id.rv_main_shop_context, item?.subtitle)
            helper.getView<TextView>(R.id.tv_main_shop_money).setText("￥${item?.max_money}".style {

            } + "    会员价${item?.min_money}元".style {
                setTextSizeRelative(0.8f)
                setTextStyle(Typeface.NORMAL)
            })
            glideImage(helper.getView(R.id.civ_main_shop), item?.picture_path ?: "")
            val rv_main_shop_tab = helper.getView<RecyclerView>(R.id.rv_main_shop_tab)
            rv_main_shop_tab.layoutManager =
                LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)
            if (rv_main_shop_tab.itemDecorationCount == 0)
                rv_main_shop_tab.addItemDecoration(
                    VerticalDividerItemDecoration.Builder(mContext).colorResId(R.color.white)
                        .sizeResId(R.dimen.dividerBig).build()
                )
            rv_main_shop_tab.adapter = ItemAdapter().apply {
                setNewData(item?.attribute?.split("，"))
            }
        }

        class ItemAdapter : BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_main_shop) {
            override fun convert(helper: BaseViewHolder, item: String?) {
                helper.setText(R.id.tv_tab, item)
            }

        }
    }
}